<!--
 * @Descripttion: 
 * @version: 
 * @Author: sueRimn
 * @Date: 2022-10-12 14:39:21
 * @LastEditors: sueRimn
 * @LastEditTime: 2023-02-27 14:41:22
-->

<template>
  <div
    class="content"
    v-loading.fullscreen.lock="fullscreenLoading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(53, 53, 53, 0.3)"
  >
    <div id="page-info"></div>
  </div>
</template>
<script>
import dt from "./data";
import Vue from "vue";
import store from "@/store";
import router from "@/router";
export default {
  name: "detailPage",
  data() {
    return {
      fullscreenLoading: false,
      allDatas: {},
      allLists: {},
      allDatasProxy: null,
      allListsProxy: null,
      requestList: [], //页面请求列表
      pageComponents: {}, //页面组件视图
      pageDetails: {}, //页面详情数据
    };
  },
  //请求暂时都放在created中  以后做成可配置的  根据请求配置项获取数据
  created() {
    let that = this;
    let dataHandler = {
      get(target, name) {
        if (target[name] === undefined) {
          target[name] = "";
        }
        return target[name];
      },
    };
    let Listhandler = {
      get(target, name) {
        if (target[name] === undefined) {
          that.$set(target, name, []);
        }
        return target[name];
      },
    };
    if (window.Proxy) {
      //运用代理可以将字符串中变量暂存在allDatas等
      this.allDatasProxy = new Proxy(this.allDatas, dataHandler);
      this.allListsProxy = new Proxy(this.allLists, Listhandler);
    } else {
      this.allDatasProxy = this.allDatas;
      this.allListsProxy = this.allLists;
    }
    this.$set(this.originObj, "allLists", this.allLists);
    // this.$set(this.originObj, "allDatas", this.allDatas);
    this.originObj.allDatas = this.allDatasProxy;
    console.log("this.route ", this.$route);
    this.initPage();
  },
  methods: {
    //发请求获取组件和视图数据，并初始化页面
    initPage() {
      this.$http.detailPage
        .getFormById(this.$address.baseUrl, {
          formId: "ec66a2b3-8247-3749-d9e2-2a93a74760c2",
        })
        .then((res) => {
          if (res.status) {
            this.pageComponents = res.data.component;
            this.requestList = res.data.requestList;
            this.loadDetailsPage();
            this.loadPageRequest();
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    loadDetailsPage(details, view) {
      //将详情数据放到allDatas中
      let pageDetails = details || this.pageDetails;
      let pageView = view || this.pageComponents;
      for (let key in pageDetails.data) {
        if (key == "list") {
          for (let k in pageDetails.data[key]) {
            this.allLists[k] = pageDetails.data[key][k];
          }
          continue;
        }
        this.allDatas[key] = pageDetails.data[key];
      }

      var originObj = this.originObj;
      var allDatas = this.allDatasProxy;
      var allLists = this.allListsProxy;
      //添加获取内容请求
      let mapBianHao = this.mapBianHao(pageView);
      let dataView = {};
      mapBianHao = eval(eval("(" + mapBianHao + ")"));
      mapBianHao.forEach((item) => {
        Object.assign(dataView, item);
      });
      this.addComponents(dataView);
    },
    mapBianHao(dt) {
      let [component, dataView] = dt.split("dataView");
      let obj = {};
      component = component.replace(
        /=["']([a-zA-Z]+?(Data|Element))/g,
        function (...arg) {
          if (!obj[arg[1]]) {
            obj[arg[1]] = {
              more: 1,
              nums: 1,
            };
          } else {
            obj[arg[1]].nums++;
          }
          return arg[0] + obj[arg[1]].nums;
        }
      );
      dataView = dataView.replace(
        /[\{\,]([a-zA-Z]+?(Data|Element))/g,
        function (...arg) {
          if (!obj[arg[1]]) {
            return arg[0];
          } else if (obj[arg[1]].nums == 1) {
            return arg[0] + obj[arg[1]].more;
          } else {
            return arg[0] + obj[arg[1]].more++;
          }
        }
      );
      return component + "dataView" + dataView;
    },
    addComponents(dataView) {
      console.log("addComponents dataView ", dataView);
      let that = this;
      import(`../../common/js/componentPackage`).then((res, rej) => {
        let components = res.default;
        console.log("components ", components);
        let template = `<div id="page-info">
        <div class="formpage" id="formpage">
              ${dataView.formPage || ""}
          </div>
          <div class="infopage" id="infopage">
            ${dataView.infoPage || ""}
          </div>
          <div class="operater-area" ref="operaterArea" id="operater-area">
            ${dataView.operaterArea || ""}
          </div>
          <div class="fixed-layout" id="fixedLayout">
            ${dataView.fixedLayout || ""}
          </div></div>`;
        let com = Vue.extend({
          template,
          components,
          data() {
            return {
              ...dataView.dataView,
            };
          },
          methods: {},
        });
        new com({
          el: "#page-info",
          router,
          store,
        }).$mount();
      });
    },
    //加载执行页面配置的请求，并将各个请求返回数据放到对应绑定数据中，绑定数据放到allLists中
    loadPageRequest() {
      if (!this.requestList) {
        //后期需处理此项不存在情况
        return;
      }
      let requestList = this.transRequestFormat(this.requestList);
      this.setRequestListToAllLists(requestList, []);
      this.fetchRequest(requestList);
    },
    //将请求中各个字段的字符串值转换成对象
    transRequestFormat(rqList) {
      if (Array.isArray(rqList) && rqList.length > 0) {
        for (let i = 0; i < rqList.length; i++) {
          if (rqList[i].bind_data_item.indexOf("[") > -1) {
            rqList[i].bind_data_item = eval(rqList[i].bind_data_item);
          } else if (rqList[i].bind_data_item.indexOf("{") > -1) {
            rqList[i].bind_data_item = eval(
              "(" + rqList[i].bind_data_item + ")"
            );
          }
          if (rqList[i].params) {
            rqList[i].params = eval("(" + rqList[i].params + ")");
          } else {
            rqList[i].params = "";
          }
          if (rqList[i].category) {
            rqList[i].category = eval("(" + rqList[i].category + ")");
          } else {
            rqList[i].category = "";
          }
        }
      }
      return rqList;
    },
    //将请求中绑定数据项等放入allLists中  resList请求执行后返回数据
    setRequestListToAllLists(rqList, resList) {
      if (!Array.isArray(rqList) || !Array.isArray(resList)) return;
      if (resList.length == 0) {
        //请求数据未返回时 初始化allLists中部分数据
        rqList.forEach((item) => {
          if (typeof item.bind_data_item == "string") {
            this.$set(this.allLists, item.bind_data_item, []);
          } else if (item.bind_data_item instanceof Array) {
            item.bind_data_item.forEach((element) => {
              this.$set(this.allLists[item.bind_data_item], element, []);
            });
          } else if (item.bind_data_item instanceof Object) {
            //后期可根据配置的策略将默认值设定为[] {}等  这里先暂时赋值成{}
            for (let key in item.bind_data_item) {
              this.$set(this.allLists, key, {});
            }
          }
        });
      } else {
        //请求数据返回后，填充到绑定数据项中
        rqList.forEach((item, index) => {
          if (typeof item.bind_data_item == "string") {
            this.$set(
              this.allLists,
              item.bind_data_item,
              JSON.parse(JSON.stringify(resList[index].data))
            );
          } else if (item.bind_data_item instanceof Array) {
            item.bind_data_item.forEach((element) => {
              this.$set(
                this.allLists[item.bind_data_item],
                element,
                ...resList[index].data
              );
            });
          } else if (item.bind_data_item instanceof Object) {
            //后期可根据配置的策略将默认值设定为[] {}等  这里先暂时赋值成{}
            for (let key in item.bind_data_item) {
              this.$set(this.allLists, key, {});
            }
          }
        });
      }
    },
    fetchRequest(rqList) {
      this.$http.detailPage
        .fetchRequest(rqList)
        .then((res) => {
          this.setRequestListToAllLists(rqList, res);
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
};
</script>